#!/usr/bin/env python

import sys
import imaplib
import getpass
import email
import email.header
import datetime
 
EMAIL_ACCOUNT = "example@mail.com"
EMAIL_FOLDER = "Demos"
EMAIL_PWD = 'pwd'
 
def process_mailbox(M):
 
    rv, data = M.search(None, "ALL")
    if rv != 'OK':
        print "No messages found!"
        return
 
    for num in data[0].split():
        rv, data = M.fetch(num, '(RFC822)')
        if rv != 'OK':
            print "ERROR getting message", num
            return
 
        msg = email.message_from_string(data[0][1])
        
        for part in msg.walk(): 
            if part.get_content_type() == "text/plain":                       
                f = open('{0}.txt'.format(num), 'w')
                f.write(part.get_payload(decode=True))
                f.close()
 
 
M = imaplib.IMAP4_SSL('imap.gmail.com')
 
try:
    rv, data = M.login(EMAIL_ACCOUNT, EMAIL_PWD)
except imaplib.IMAP4.error:
    print "LOGIN FAILED!!! "
    sys.exit(1)
 
print rv, data
 
# rv, mailboxes = M.list()
# if rv == 'OK':
#     print "Mailboxes:"
#     print mailboxes
 
rv, data = M.select(EMAIL_FOLDER)
if rv == 'OK':
    print "Processing mailbox...\n"
    process_mailbox(M)
    M.close()
else:
    print "ERROR: Unable to open mailbox ", rv
 
M.logout()